﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;
using PostSharp.Laos;
using PostSharp.Extensibility;


namespace PostSharpModel.Property
{
    [Serializable]
    [MulticastAttributeUsage(MulticastTargets.Method)]
    public class PropertyModifyAttribute : OnMethodBoundaryAspect
    {
        private object preValue;

        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            base.OnEntry(eventArgs);

            //记录属性更改前的值
            if (!eventArgs.Method.IsSpecialName)
                return;
            if (!eventArgs.Method.Name.StartsWith("set_"))
                return;
            string property = eventArgs.Method.Name.Substring(4);
            this.preValue = this.GetPropertyValue(eventArgs.Instance, property);
        }

        public override void OnExit(MethodExecutionEventArgs eventArgs)
        {
            base.OnExit(eventArgs);
            if (!eventArgs.Method.IsSpecialName)
                return;
            if (!eventArgs.Method.Name.StartsWith("get_") & !eventArgs.Method.Name.StartsWith("set_"))
                return;

            bool isSetter = eventArgs.Method.Name.StartsWith("set_");
            string property = eventArgs.Method.Name.Substring(4);

            if (isSetter)
                Console.WriteLine("属性 \"{0}\" 从原来的\"{1}\" 改变为现在的 \"{2}\"。",
                    property, this.preValue, this.GetPropertyValue(eventArgs.Instance, property));
            else
                Console.WriteLine("属性 \"{0}\" 已读", property);
        }

        private object GetPropertyValue(object instance, string property)
        {
            PropertyInfo getter = instance.GetType().GetProperty(property);
            return getter.GetValue(instance, null);
        }
    }
}
